package com.artPreter.utils;

import cn.hutool.core.codec.Base64;
import com.artPreter.pojo.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class HttpUtil {
    private HttpUtil(){}

    /** 超时时间5分钟 **/
    private static final int milliseconds = 300000;

    private final static String TOKEN_NAME = "lvt_token=";

    /**
     * get请求
     * @param url
     * @return
     */
    public static HttpResult httpClientGet(String url) {
        log.info("\nGET请求URL：{}", url);

        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(getRequestConfig()).build()) {
            try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
                String bodyData = StringUtils.toEncodedString(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8);
                log.info("\nGET请求返回结果，status：{}，body：{}", response.getCode(), bodyData);
                HttpResult httpResult = new HttpResult(response.getCode(), bodyData);
                return httpResult;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * get请求
     * @param url
     * @param token
     * @return  HttpResult
     */
    public static HttpResult httpClientGet(String url, String token) {
        log.info("\nGET请求URL：{} ,token:{}", url,token);

        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("cookie",TOKEN_NAME + token);
        httpGet.setHeader("Authorization", "Bearer " + token);
        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(getRequestConfig()).build()) {
            try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
                String bodyData = StringUtils.toEncodedString(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8);
                log.info("\nGET请求返回结果，status：{}，body：{}", response.getCode(), bodyData);
                HttpResult httpResult = new HttpResult(response.getCode(), bodyData);
                return httpResult;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * get请求
     * @param url
     * @param userName
     * @param password
     * @return  HttpResult
     */
    public static HttpResult httpClientGet(String url, String userName, String password){
        log.info("\nGET请求URL：{}", url);

        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Authorization", "Basic " + Base64.encode(userName + ":" + password));
        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(getRequestConfig()).build()) {
            try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
                String bodyData = StringUtils.toEncodedString(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8);
                log.info("\nGET请求返回结果，status：{}，body：{}", response.getCode(), bodyData);
                HttpResult httpResult = new HttpResult(response.getCode(), bodyData);
                return httpResult;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static RequestConfig getRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(milliseconds, TimeUnit.MILLISECONDS)
                .setResponseTimeout(milliseconds, TimeUnit.MILLISECONDS)
                .setConnectionRequestTimeout(milliseconds, TimeUnit.MILLISECONDS)
                .build();
    }


    /**
     * get请求自动组装参数
     * @param url
     * @param paramMap
     * @param userName
     * @param password
     * @return  HttpResult
     */
    public static HttpResult httpClientGet(String url, Map<String, Object> paramMap, String userName, String password) {
        return httpClientGet(assemblyGetUrl(url, paramMap), userName, password);
    }

    /**
     * get请求自动组装参数
     * @param url
     * @param paramMap
     * @return HttpResult
     */
    public static HttpResult httpClientGet(String url, Map<String, Object> paramMap) {
        return httpClientGet(assemblyGetUrl(url, paramMap));
    }

    public static String assemblyGetUrl(String url, Map<String, Object> paramMap) {
        StringBuffer sb = new StringBuffer(url);
        boolean first = true;
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            if(first) {
                sb.append("?");
            } else {
                sb.append("&");
            }
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue());
            first = false;
        }
        return sb.toString();
    }
}

